import React, { useEffect, useMemo, useState } from 'react'
import { Input, Button, Toast, Image } from 'react-vant'
import { createFromIconfontCN } from '@react-vant/icons'
import '../css3/Dialogue.scss'
import { useLocation, useNavigate } from 'react-router-dom'
import { io } from "socket.io-client";

import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:3000'

const IconFont = createFromIconfontCN('//at.alicdn.com/t/c/font_4418635_x36bepkdcp.js')

export default function Dialogue() {
  const navigate = useNavigate()
  const [text, setText] = useState('')
  const [messages, setMessages] = useState([])
  const user = JSON.parse(sessionStorage.getItem("user"))
  const friend = JSON.parse(sessionStorage.getItem("friend"))

  const socket = io('http://localhost:3000', {
    query: {
      userId: user._id,
    },
    extraHeaders: {
      "Access-Control-Allow-Origin": "*"
    }
  })


  const showDate = (() => {
    const now = new Date()
    const y = now.getFullYear()
    const m = now.getMonth() + 1
    const d = now.getDate()
    const h = now.getHours()
    const mi = now.getMinutes()

    return y + '-' + (m < 10 ? '0' + m : m) + '-' + d + ' ' + (h < 10 ? '0' + h : h) + ':' + (mi < 10 ? '0' + mi : mi)
  })


  const sendMessage = (type) => {
    switch (type) {
      case "message":
        if (!text) return Toast.info('发送内容不能为空!')
        socket.emit('send', {
          info: {
            date: showDate(),
            msg: text,
            formUsername: user.username,
            sendUsername: friend.username,
            formImg: user.picture,
            sendImg: friend.picture,
            uid: user._id + friend._id,
            sid: friend._id + user._id,
            formId: user._id,
            sendId: friend._id,
          },
          type: 'message'
        })
        setText("")
        break
      case "video":
        socket.emit('send', {
          info: {
            appId: "eeaea820dab04ca497e18788de1e572f",   // 存储 App ID的状态
            channel: "video",   // 存储频道名的状态
            token: "007eJxTYEj3ySlo/sE7ZVW0yY+XzFGa65vbb0gwC4a8dWNcKdYZx67AkJqamJpoYWSQkphkYJKcaGJpnmpoYW5hkZJqmGpqbpT2+mp/WkMgI8PCWasYGKEQxGdlKMtMSc1nYAAA/8MfMg==",   // 存储Token 的状态
          },
          type: 'video'
        })
        navigate('/exchange', { state: { title: '等待接听...', type: 'dial' } })
        break
    }
  }


  socket.on('receive', (data) => {
    switch (data.type) {
      case "message":
        setMessages([...messages, data.info])
        break
      case "video":
        navigate('/exchange', { state: { title: `${friend.username}来电...`, type: 'answer' } })
        break
    }
  })


  const getMessage = async () => {
    const { data: { code, messageList } } = await axios.post('/message', { formId: user._id, uid: (user._id + friend._id), sid: (friend._id + user._id) })
    code === 200 ? setMessages(messageList) : Toast.fail('获取信息失败')
  }
  useEffect(() => {
    getMessage()
  }, [])

  return (
    <div id='dialogue' >

    <div id="head">
      <IconFont name='icon-zuojiantou'
        onClick={() => navigate('/message')}
      />
      <h3><Image width={40} height={40} round src={friend.picture} />{friend.username}</h3>
      <IconFont
        name='icon-shipin'
        onClick={() => sendMessage('video')}
      />
    </div>


    <div id="content">
      {
        messages.map((item, index) => (
          <dl className={item.formId === user._id ? 'right' : 'left'} key={index}>
            {
              item.formId === user._id ? 
              <div className='right'>
                <dd>
                  <p>{item.msg}</p>
                  <p className='date'>{item.date}</p>
                </dd>
                <dt>
                  <Image src={item.id === user.id ? item.sendImg : item.formImg} width={50} height={50} round />
                </dt>
              </div> 
              : 
              <div className='left'>
                <dt>
                  <Image src={item.id === user.id ? item.sendImg : item.formImg} width={50} height={50} round />
                </dt>
                <dd>
                  <p>{item.msg}</p>
                  <p className='date'>{item.date}</p>
                </dd>
              </div>
            }

          </dl>
        ))
      }
    </div>

    <div id="bottom">
      <IconFont name='icon-xiazai8' />
      <IconFont name='icon-biaoqing' />
      <Input
        value={text}
        onChange={(val) => setText(val)}
        style={{ width: "66vw" }}
      />
      <IconFont
        onClick={() => sendMessage('message')}
        name='icon-fasong'
      />
    </div>

  </div >
  )
}
